package com.tg.service.eventbus2;

import com.google.common.eventbus.EventBus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

public class ComponentBus extends EventBus {

    private static final Logger LOGGER = LoggerFactory.getLogger(ComponentBus.class);

    public static final ComponentBus of() {
        return new ComponentBus();
    }

    private String eventName;

    private List<Component> components;

    public List<Component> getComponents() {
        return components;
    }

    public ComponentBus setComponents(List<Component> components) {
        this.components = components;
        return this;
    }

    public ComponentBus setEventName(String eventName) {
        this.eventName = eventName;
        return this;
    }

    public ComponentBus init() {
        if (!CollectionUtils.isEmpty(this.components)) {
            this.components.forEach(this::register);
            String taskNames = this.components.stream().map(baseTask -> baseTask.getClass().getSimpleName()).collect(Collectors.joining("->"));
            LOGGER.info("事件【{}】注册组件链：{}", this.eventName, taskNames);
        } else {
            String msg = String.format("事件【%s】业务链配置异常", this.eventName);
            LOGGER.warn(msg);
            throw new IllegalArgumentException(msg);
        }
        return this;
    }
}
